package com.kob.backend.controller.chat;

import com.kob.backend.pojo.Message;

import com.kob.backend.service.user.chat.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController

public class ChatMessageController {

    @Autowired
    private ChatMessageService chatMessageService;

    @GetMapping("/getMessages")
    @CrossOrigin(origins = "http://localhost:8080") // 允许跨域请求从指定源

    private List<Message> getMessages() {
        return chatMessageService.getMessages();
    }


    @PostMapping("/postMessage")  // 修改为POST请求
    @CrossOrigin(origins = "http://localhost:8080") // 允许跨域请求从指定源

    private Map<String, String> postMessage(@RequestBody Message message) {
        Map<String, String> result = new HashMap<>();
        if (message.getAuthor().trim().isEmpty() || message.getMessage().trim().isEmpty()) {
            // 验证留言作者和内容是否为空
            result.put("status", "failed");
            result.put("message", "Author and message content must not be empty.");
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            message.setTime(dateFormat.format(new Date()));

            result = chatMessageService.postMessage(message);

            if ("success".equals(result.get("status"))) {
                // 处理留言成功逻辑，例如刷新留言列表
                List<Message> updatedMessages = chatMessageService.getMessages();
                // 可以将 updatedMessages 返回给前端或者进行其他处理

            } else {
                String errorMessage = result.get("message");
                System.out.println("留言失败：" + errorMessage); // 打印错误消息到控制台
            }
        }

        return result;
    }

}
